<template xmlns="http://www.w3.org/1999/html">
  <div class="data-summary" style="padding: 20px">
    <!-- 综合信息摘要（增强版） -->
    <el-card class="mb-3">
      <template #header>
        <div class="card-header" style="display: flex; justify-content: space-between; align-items: center">
          <span>综合信息摘要：被查询人（{{ name }}）</span>
          <!-- 按钮区域 -->
          <div style="display: flex; gap: 10px">
            <el-button type="primary" @click="$router.back()" size="big">返回</el-button>
            <el-button type="success" @click="exportData" size="big">综合数据导出</el-button>
            <el-button type="info" @click="goToPage('manage2')" size="big">送达与拘传指引</el-button>
            <el-button type="warning" @click="goToPage('manage3')" size="big">关联人财产查询</el-button>
            <el-button type="danger" @click="goToPage('manage4')" size="big">清场辅助与评估</el-button>
          </div>
        </div>
      </template>
      <el-card>
        <div style="
            background-color: #fff7f7;
            border: 1px solid #f56c6c;
            padding: 10px;
            border-radius: 6px;
            color: #f56c6c;
            margin: 15px;
          ">
          <strong>预警提醒：</strong>
          常住地址{{
            predictedAddress && predictedAddress !== "无信息" ? "已知" : "未知"
          }}{{
            predictedAddress && predictedAddress !== "无信息" ? "可以" : "暂时不能"
          }}拘传， {{ relatedPeople.length > 0 ? "存在" : "不存在" }}财产关联人等
        </div>
        <!-- 履行能力综合打分（红色圆圈） -->
        <div style="display: flex; align-items: center; margin-bottom: 15px">
          <div v-if="isDataLoaded" :style="{ background: getPerformanceColor() }" style="
            width: 60px;
            height: 60px;
            border-radius: 50%;
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: bold;
            font-size: 20px;
            margin-right: 10px;
          ">
            {{ getPerformanceLevel() }}
          </div>
          <span>
            <strong>履行能力等级：</strong>
            当前评估为
            <span :style="{ color: getPerformanceColor(), fontWeight: 'bold' }">
              {{ getPerformanceText() }}
            </span>
          </span>
        </div>
        <strong>特殊情况提醒：</strong>
        <div v-if="specialEvents.length > 0" style="color: #f56c6c; margin-top: 5px">
          <ul style="list-style: none; padding-left: 0">
            <li v-for="(event, index) in specialEvents" :key="index">
              {{ event }}
            </li>
          </ul>
        </div>
        <div v-else style="color: #999">暂无异常变动记录</div>
      </el-card>
      <el-card>
        <template #header>
          <div class="card-header">
            <span>鱼骨图分析</span>
            <el-button type="primary" @click="toggleFishbone" size="big" style="float: right">
              {{ showFishbone ? "收起" : "展开" }}鱼骨图
            </el-button>
          </div>
        </template>
        <div v-show="showFishbone" style="height: auto;">
          <FishboneDiagram :id-number="idNumber" :name="name" :phone="phone" />
        </div>
      </el-card>
      <div style=" display: flex; justify-content: space-between;">
        <el-card style="width: 33%;">
          <strong>详细个人信息</strong>
          <div style="
                    border: 1px solid #ebeef5;
                    padding: 10px;
                    border-radius: 6px;
                  ">
            <div style="font-size: 12px; margin-top: 5px">
              <el-table :data="personalInfoTableData" style="width: 100%" border :show-header="false">
                <el-table-column prop="field1" label="" width="80">
                  <template #default="scope">
                    <strong>{{ scope.row.field1 }}</strong>
                  </template>
                </el-table-column>
                <el-table-column prop="value1" label=""></el-table-column>
                <el-table-column prop="field2" label="" width="80">
                  <template #default="scope">
                    <strong>{{ scope.row.field2 }}</strong>
                  </template>
                </el-table-column>
                <el-table-column prop="value2" label=""></el-table-column>
              </el-table>
            </div>
          </div>
        </el-card>
        <el-card style="width: 33%;">
          <strong>位置段频次</strong>
          <el-table :data="addressFrequencyData" border style="font-size: 12px">
            <el-table-column prop="address" label="地址" show-overflow-tooltip></el-table-column>
            <el-table-column prop="count" label="频次" width="60"></el-table-column>
          </el-table>
        </el-card>
        <el-card style="width: 33%;">
          <strong>在家时间段</strong>
          <div ref="chartRefHomeTimeSmall" style="height: 400px"></div>
        </el-card>
      </div>
      <div style="display: flex; justify-content: space-between;">
        <el-card style="width: 33%;">
          <strong>关联人信息</strong>
                <div v-if="relatedPeople.length > 0" style="margin-top: 5px">
                  <el-table :data="currentRelatedPeople" style="width: 100%; font-size: 12px" border>
                    <el-table-column prop="recName" label="姓名"></el-table-column>
                    <el-table-column label="关系">
                      <template #default="scope">
                        {{ getRelation(scope.row.recName) }}
                      </template>
                    </el-table-column>
                    <el-table-column prop="recPhone" label="电话">
                      <template #default="scope">
                        {{ scope.row.recPhone || "无电话" }}
                      </template>
                    </el-table-column>
                  </el-table>
                </div>
                <div v-else style="color: #999">暂无关联人信息</div>
                <div class="block" style="margin-top: 10px; text-align: right">
                  <el-pagination layout="prev, pager, next" :hide-on-single-page="relatedPeople.length <= 5"
                    :total="relatedPeople.length" :page-size="5" :current-page="currentPage"
                    @current-change="handlePageChange">
                  </el-pagination>
                </div>
        </el-card>
        <el-card style="width: 33%;">
          <strong>家属信息</strong>
                <div v-if="personalInfo && Object.keys(personalInfo).length > 0" style="margin-top: 5px">
                  <el-table :data="householdMembers" style="width: 100%; font-size: 12px" border>
                    <el-table-column prop="name" label="姓名"></el-table-column>
                    <el-table-column prop="relationship" label="关系"></el-table-column>
                    <el-table-column prop="phone" label="电话"></el-table-column>
                  </el-table>
                </div>
                <div v-else style="color: #999">暂无家属信息</div>
        </el-card>
        <el-card style="width: 33%;">
          <strong>个人企业信息</strong>
            <PersonalEnterprise :data="filteredEnterpriseInfo" :page-size="5" />
        </el-card>
      </div>

      <div style="display: flex; justify-content: space-between;">
        <el-card style="width: 49.8%">
          <strong>停车信息</strong>
              <ParkingInfo :id-number="idNumber" />
          </el-card>  
          <el-card style="width: 49.8%">
            <strong>车辆信息</strong>
              <VehicleInfo :id-number="idNumber" />
          </el-card>
      </div>

      <div style="display: flex; justify-content: space-between;">
        <el-card style="width: 33%">
          <strong>统计信息</strong>
                    <el-table :data="propertyStatsTableData" style="width: 100%" border :show-header="false">
                      <el-table-column prop="field1" label="" width="100">
                        <template #default="scope">
                          <strong>{{ scope.row.field1 }}</strong>
                        </template>
                      </el-table-column>
                      <el-table-column prop="value1" label=""></el-table-column>
                      <el-table-column prop="field2" label="" width="100">
                        <template #default="scope">
                          <strong>{{ scope.row.field2 }}</strong>
                        </template>
                      </el-table-column>
                      <el-table-column prop="value2" label=""></el-table-column>
                    </el-table>

        </el-card>
        <el-card style="width: 33%;">
          <strong>社保参保信息</strong>
                  <el-table :data="paginatedLetterInfo" border stripe
                    style="width: 100%; font-size: 12px; margin-top: 10px" :empty-text="'暂无数据'">
                    <el-table-column prop="currentInsuranceDate" label="参保时间" width="120"></el-table-column>
                    <el-table-column prop="unitName" label="参保单位" show-overflow-tooltip></el-table-column>
                    <el-table-column prop="insuranceType" label="参保类型" width="100"></el-table-column>
                    <el-table-column prop="insuranceStatus" label="参保状态" width="100"></el-table-column>
                  </el-table>
                  <div style="margin-top: 10px; text-align: right">
                    <el-pagination layout="prev, pager, next, jumper, total" :total="letterInfo.length"
                      :page-size="letterInfoPageSize" :current-page="letterInfoCurrentPage"
                      @current-change="(page) => letterInfoCurrentPage = page" :page-sizes="[10, 20, 50]"
                      @size-change="(size) => letterInfoPageSize = size" small>
                    </el-pagination>
                  </div>
        </el-card>
        <el-card style="width: 33%;">
          <strong>医保使用信息</strong>
                  <el-table :data="paginatedUsageInfo" border stripe
                    style="width: 100%; font-size: 12px; margin-top: 10px" :empty-text="'暂无数据'">
                    <el-table-column prop="startDate" label="使用时间" width="100"></el-table-column>
                    <el-table-column prop="designatedMedicalInstitutionName" label="医疗机构"
                      show-overflow-tooltip></el-table-column>
                    <el-table-column prop="totalMedicalExpenses" label="医保支付(元)" width="90"></el-table-column>
                    <el-table-column prop="fullSelfPayAmount" label="自费支付(元)" width="90"></el-table-column>
                    <el-table-column prop="balance" label="账户余额(元)" width="100"></el-table-column>
                  </el-table>
                  <div style="margin-top: 10px; text-align: right">
                    <el-pagination layout="prev, pager, next, jumper, total" :total="usageInfo.length"
                      :page-size="usageInfoPageSize" :current-page="usageInfoCurrentPage"
                      @current-change="(page) => usageInfoCurrentPage = page" :page-sizes="[10, 20, 50]"
                      @size-change="(size) => usageInfoPageSize = size" small>
                    </el-pagination>
                  </div>
          </el-card>
      </div>
      <div style="display: flex; justify-content: space-between;">
        <el-card style="width: 33%">
          <strong>居民缴费信息</strong>
                  <el-table :data="paginatedResidentInfo" border stripe
                    style="width: 100%; font-size: 12px; margin-top: 10px" :empty-text="'暂无数据'">
                    <el-table-column prop="handlingTime" label="缴费时间" width="150"></el-table-column>
                    <el-table-column prop="taxUnitName" label="缴费地区" show-overflow-tooltip></el-table-column>

                    <el-table-column prop="paymentAmount" label="缴费金额(元)" width="100"></el-table-column>
                  </el-table>
                  <div style="margin-top: 10px; text-align: right">
                    <el-pagination layout="prev, pager, next, jumper, total" :total="residentInfo.length"
                      :page-size="residentInfoPageSize" :current-page="residentInfoCurrentPage"
                      @current-change="(page) => residentInfoCurrentPage = page" :page-sizes="[10, 20, 50]"
                      @size-change="(size) => residentInfoPageSize = size" small>
                    </el-pagination>
                  </div>
        </el-card>
        <el-card style="width: 33%;">
          <strong>房产信息</strong>
                  <el-table :data="paginatedRealEstateInfo" border stripe
                    style="width: 100%; font-size: 12px; margin-top: 10px" :empty-text="'暂无数据'">
                    <el-table-column prop="address" label="地址" show-overflow-tooltip></el-table-column>
                    <el-table-column prop="buildingArea" label="建筑面积(㎡)" width="100"></el-table-column>
                    <el-table-column prop="mortgageAmount" label="贷款金额" width="100"></el-table-column>
                    <el-table-column prop="landPurpose" label="土地用途" width="120"></el-table-column>
                    <el-table-column prop="isSeized" label="查封状态" width="100">
                      <template #default="scope">
                        <span :style="{ color: scope.row.isSeized === '是' ? '#f56c6c' : '#67c23a' }">
                          {{ scope.row.isSeized }}
                        </span>
                      </template>
                    </el-table-column>
                  </el-table>
                  <div style="margin-top: 10px; text-align: right">
                    <el-pagination layout="prev, pager, next, jumper, total" :total="uniqueRealEstateInfo.length"
                      :page-size="realEstatePageSize" :current-page="realEstateCurrentPage"
                      @current-change="(page) => realEstateCurrentPage = page" :page-sizes="[10, 20, 50]"
                      @size-change="(size) => realEstatePageSize = size" small>
                    </el-pagination>
                  </div>
        </el-card>
        <el-card style="width: 33%">
          <strong>船舶信息</strong>
                  <el-table :data="processedShipInfo" border stripe
                    style="width: 100%; font-size: 12px; margin-top: 10px" :empty-text="'暂无船舶登记信息'">
                    <el-table-column prop="shipName" label="船舶名称" show-overflow-tooltip></el-table-column>
                  </el-table>
        </el-card>

      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from "vue";
import { useRoute, useRouter } from "vue-router";
import { watch } from 'vue';
import axios from "axios";
import * as echarts from "echarts";
import { ElMessage } from "element-plus";
import FishboneDiagram from "./Tableyugu.vue"; // 引入鱼骨图组件
import { useGlobalParamsStore } from '@/store/globalParams';
import ParkingInfo from './ParkingInfo.vue';
import VehicleInfo from "./VehicleInfo.vue";
import PersonalEnterprise from "./PersonalEnterpriseInfo.vue";
// 全局地址
const globalStore = useGlobalParamsStore();
watch(
    () => globalStore.globalAddress,
    (newVal) => {
      console.log("========= 数据更新了！当前总数:", newVal.length, "=========");
      console.log("最新数据列表：", newVal);
    },
    { deep: true } // 深度监听数组内部变化
);
const route = useRoute();
const router = useRouter();
const idNumber = ref(route.query.idNumber);
const name = ref(route.query.name);
const phone = ref(route.query.phone);
const personalInfo = ref({});
const householdMembers = computed(() => {
  if (!personalInfo.value || Object.keys(personalInfo.value).length === 0) {
    return [];
  }

  const members = [];
  for (let i = 1; i <= 7; i++) {
    const name = personalInfo.value[`householdMember${i}Name`];
    if (name) {
      members.push({
        name: name,
        relationship: personalInfo.value[`householdMember${i}Relationship`] || "未知",
        phone: personalInfo.value[`householdMember${i}Phone`] || "无",
      });
    }
  }
  return members;
});

const propertyStatsTableData = computed(() => {
  const rows = [];

  // 第一行：房产信息
  rows.push({
    field1: '房产',
    value1: `${getUniqueRealEstateCount(realEstateInfo.value)} 处，其中 ${realEstateInfo.value.filter((r) => r && r.isSeized === "是").length} 处已被查封`,
    field2: '船舶',
    value2: shipInfo.value.length > 0
      ? shipInfo.value[0].shipName === "未在本登记机关查询到有登记船舶信息"
        ? "无"
        : shipInfo.value[0].shipName
      : "无"
  });

  // 第二行：保险和缴费信息
  rows.push({
    field1: '社保参保',
    value1: `${letterInfo.value.length} 次`,
    field2: '医保使用',
    value2: `${usageInfo.value.length} 次`
  });

  // 第三行：居民缴费
  rows.push({
    field1: '居民缴费',
    value1: `${residentInfo.value.length} 次`,
    field2: '',
    value2: ''
  });

  return rows;
});


// 财产信息
// 按时间倒序排列的社保参保信息
const sortedLetterInfo = computed(() => {
  if (!letterInfo.value || letterInfo.value.length === 0) {
    return [];
  }

  return [...letterInfo.value].sort((a, b) => {
    return new Date(b.currentInsuranceDate) - new Date(a.currentInsuranceDate);
  });
});

// 按时间倒序排列的医保使用信息，时间相同时按余额升序排列
const sortedUsageInfo = computed(() => {
  if (!usageInfo.value || usageInfo.value.length === 0) {
    return [];
  }

  return [...usageInfo.value].sort((a, b) => {
    const dateA = new Date(a.startDate);
    const dateB = new Date(b.startDate);

    // 首先按时间倒序排列
    if (dateB - dateA !== 0) {
      return dateB - dateA;
    }

    // 时间相同时，按余额升序排列（余额少的在前面）
    const balanceA = parseFloat(a.balance) || 0;
    const balanceB = parseFloat(b.balance) || 0;
    return balanceA - balanceB;
  });
});


// 社保参保信息分页
const letterInfoCurrentPage = ref(1);
const letterInfoPageSize = ref(10);

// 医保使用信息分页
const usageInfoCurrentPage = ref(1);
const usageInfoPageSize = ref(10);

// 计算社保参保信息分页数据
const paginatedLetterInfo = computed(() => {
  if (!sortedLetterInfo.value || sortedLetterInfo.value.length === 0) {
    return [];
  }

  const start = (letterInfoCurrentPage.value - 1) * letterInfoPageSize.value;
  const end = start + letterInfoPageSize.value;
  return sortedLetterInfo.value.slice(start, end);
});

// 计算医保使用信息分页数据
const paginatedUsageInfo = computed(() => {
  if (!sortedUsageInfo.value || sortedUsageInfo.value.length === 0) {
    return [];
  }

  const start = (usageInfoCurrentPage.value - 1) * usageInfoPageSize.value;
  const end = start + usageInfoPageSize.value;
  return sortedUsageInfo.value.slice(start, end);
});

// 房产信息分页
const realEstateCurrentPage = ref(1);
const realEstatePageSize = ref(10);

// 获取去重后的房产信息
const uniqueRealEstateInfo = computed(() => {
  return deduplicateRealEstate(realEstateInfo.value);
});

// 计算房产信息分页数据
const paginatedRealEstateInfo = computed(() => {
  if (!uniqueRealEstateInfo.value || uniqueRealEstateInfo.value.length === 0) {
    return [];
  }

  const start = (realEstateCurrentPage.value - 1) * realEstatePageSize.value;
  const end = start + realEstatePageSize.value;
  return uniqueRealEstateInfo.value.slice(start, end);
});

// 格式化数字显示
const formatNumber = (row, column, value) => {
  if (value === null || value === undefined) return '-';
  return parseFloat(value).toFixed(2);
};



// 按时间倒序排列的居民缴费信息
const sortedResidentInfo = computed(() => {
  if (!residentInfo.value || residentInfo.value.length === 0) {
    return [];
  }

  return [...residentInfo.value].sort((a, b) => {
    return new Date(b.handlingTime) - new Date(a.handlingTime);
  });
});

// 居民缴费信息分页
const residentInfoCurrentPage = ref(1);
const residentInfoPageSize = ref(10);

// 计算居民缴费信息分页数据
const paginatedResidentInfo = computed(() => {
  if (!sortedResidentInfo.value || sortedResidentInfo.value.length === 0) {
    return [];
  }

  const start = (residentInfoCurrentPage.value - 1) * residentInfoPageSize.value;
  const end = start + residentInfoPageSize.value;
  return sortedResidentInfo.value.slice(start, end);
});

// 船舶信息处理
const processedShipInfo = computed(() => {
  if (!shipInfo.value || shipInfo.value.length === 0) {
    return [];
  }

  // 过滤掉"未在本登记机关查询到有登记船舶信息"的记录
  return shipInfo.value.filter(ship =>
    ship.shipName && ship.shipName !== "未在本登记机关查询到有登记船舶信息"
  );
});



// 控制鱼骨图显示/隐藏
const showFishbone = ref(true);

// 切换鱼骨图显示状态
const toggleFishbone = () => {
  showFishbone.value = !showFishbone.value;
};

// 修改导出数据方法，显示成功提示
const exportData = () => {
  if (!idNumber.value || !name.value) {
    ElMessage.error("缺少必要的人员信息");
    return;
  }

  // 构造请求数据
  const requestData = {
    idNumber: idNumber.value,
    name: name.value,
  };
  if (name.value === '李沛桐') {
    const filePath = '/李沛桐研判报告(10.7).docx'
    const link = document.createElement('a');
    link.href = filePath;
    link.download = '李沛桐研判报告';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    return;
  }

  // 发送请求到后端生成PDF，使用完整路径，不经过/api代理
  axios
    .post("http://localhost:8090/report/generate-person-report", requestData, {
      responseType: "blob", // 重要：指定响应类型为blob以处理文件下载
    })
    .then((response) => {
      // 创建一个Blob对象
      const blob = new Blob([response.data], { type: "application/pdf" });

      // 创建下载链接
      const url = window.URL.createObjectURL(blob);
      const link = document.createElement("a");
      link.href = url;
      link.setAttribute("download", `${name.value}情况报告.pdf`);

      // 触发下载
      document.body.appendChild(link);
      link.click();

      // 清理
      window.URL.revokeObjectURL(url);
      document.body.removeChild(link);

      ElMessage.success("导出成功！");
    })
    .catch((error) => {
      console.error("导出PDF失败:", error);
      ElMessage.error("导出失败，请重试");
    });
};

const goToHome = () => {
  router.push({ name: "manage1" });
};

// 各类数据
const usageInfo = ref([]);
const shipInfo = ref([]);
const residentInfo = ref([]);
const realEstateInfo = ref([]);
const letterInfo = ref([]);
const caseInfo = ref([]);
const familyInfo = ref([]);
const specialEvents = ref([]);
const relatedPeople = ref([]);
const personEnterpriseInfo = ref([]); // 个人企业信息
const isDataLoaded = ref(false);
const selfAddressFrequency = ref([]); // 本人地址交互频次
const currentPage = ref(1);
const currentRelatedPeople = computed(() => {
  const startIndex = (currentPage.value - 1) * 5;
  const endIndex = startIndex + 5;
  return relatedPeople.value.slice(startIndex, endIndex);
});
const handlePageChange = (page) => {
  currentPage.value = page;
};
// 过滤后的企业信息（只显示法定代表人是自己的企业）
const filteredEnterpriseInfo = computed(() => {
  if (!personEnterpriseInfo.value || personEnterpriseInfo.value.length === 0) {
    return [];
  }

  // 过滤法定代表人是自己的企业
  return personEnterpriseInfo.value.filter((item) => {
    // 检查法定代表人字段是否匹配当前用户姓名
    return item.legalRepresentative && item.legalRepresentative.includes(name.value);
  });
});

const personalInfoTableData = computed(() => {
  if (!personalInfo.value || Object.keys(personalInfo.value).length === 0) {
    return [];
  }

  const info = personalInfo.value;
  const fields = [
    { field: 'birthDate', label: '出生日期' },
    { field: 'ethnicity', label: '民族' },
    { field: 'gender', label: '性别' },
    { field: 'nativePlace', label: '籍贯' },
    { field: 'birthplace', label: '出生地' },
    { field: 'militaryService', label: '兵役状况' },
    { field: 'educationLevel', label: '教育程度' },
    { field: 'maritalStatus', label: '婚姻状况' },
    { field: 'height', label: '身高' },
    { field: 'politicalStatus', label: '政治面貌' },
    { field: 'religion', label: '宗教信仰' },
    { field: 'workplace', label: '服务处所' },
    { field: 'position', label: '职务' }
  ];

  const rows = [];
  for (let i = 0; i < fields.length; i += 2) {
    const row = {
      field1: fields[i].label,
      value1: info[fields[i].field] || '未知',
    };

    if (i + 1 < fields.length) {
      row.field2 = fields[i + 1].label;
      row.value2 = info[fields[i + 1].field] || '未知';
    } else {
      row.field2 = '';
      row.value2 = '';
    }

    rows.push(row);
  }

  return rows;
});


// 汇总统计
const summaryStats = ref({
  caseCount: 0,
  propertyCount: 0,
  insuranceCount: 0,
  residentPaymentCount: 0,
});

// 图表实例
const chartRefHomeTimeSmall = ref(null);

let homeTimeInstanceSmall = null;

// 预测结果
const predictedAddress = ref("无信息"); // 默认改为"无信息"

// 地址频次数据
const addressFrequencyData = computed(() => {
  console.log("selfAddressFrequency.value:", selfAddressFrequency.value);
  if (!selfAddressFrequency.value || selfAddressFrequency.value.length === 0) {
    return [{ address: "暂无地址信息", count: 0 }];
  }

  // 转换数据格式以匹配前端期望的字段名
  const convertedData = selfAddressFrequency.value.map((item) => ({
    address: item.recAddress || "未知地址",
    count: item.frequency || 0,
  }));

  // 按频次从高到低排序
  const sortedData = [...convertedData].sort((a, b) => b.count - a.count);

  // 只取前几条数据展示
  const result = sortedData.slice(0, 5);
  console.log("addressFrequencyData result:", result);
  return result;
});

// 跳转页面
const goToPage = (pageName) => {
  router.push({
    name: pageName,
    query: {
      idNumber: idNumber.value,
      name: name.value,
      phone: phone.value,
      from: "dataSummary",
    },
  });
};

// 获取亲属关系
const getRelation = (name) => {
  if (name.includes("刘美琳")) return "配偶";
  if (name.includes("张伟")) return "兄弟";
  return "点单";
};

// 加载数据
const loadData = () => {
  if (!idNumber.value) {
    console.error("未提供身份证号");
    return;
  }

  // 创建一个 Promise 数组，收集所有异步请求
  const promises = [];

  // 1. 加载主要数据
  promises.push(
    axios
      .post(`/api/query/id`, { idNumber: idNumber.value })
      .then((response) => {
        const data = response.data.data;
        console.log("数据加载成功:", data);

        usageInfo.value = data.usageInfo || [];
        shipInfo.value = data.shipInfo || [];
        residentInfo.value = data.residentInfo || [];
        letterInfo.value = data.letterInfo || [];
        caseInfo.value = data.caseInfo || [];

        realEstateInfo.value = deduplicateRealEstate(data.realEstateInfo || []);

        familyInfo.value = data.familyInfo || [];
        specialEvents.value = data.specialEvents || [];

        const uniqueRealEstateCount = getUniqueRealEstateCount(realEstateInfo.value);
        summaryStats.value = {
          caseCount: caseInfo.value.length,
          propertyCount: uniqueRealEstateCount,
          insuranceCount: letterInfo.value ? letterInfo.value.length : 0,
          residentPaymentCount: residentInfo.value ? residentInfo.value.length : 0,
        };
      })
      .catch((error) => {
        console.error("数据加载失败:", error);
      })
  );

  // 2. 加载关联人数据
  promises.push(
    axios
      .post("/api/relatedPeople/all", {
        phone: phone.value,
      })
      .then((response) => {
        const result = response.data;
        console.log("关联人数据加载成功:", result);
        relatedPeople.value = result.result || [];
      })
      .catch((error) => {
        console.error("关联人数据加载失败:", error);
      })
  );

  // 3. 加载美团数据
  promises.push(
    axios
      .post("/api/caseInformation/summon", {
        executor: name.value,
        phone: phone.value,
        idNumber: idNumber.value,
      })
      .then((response) => {
        const result = response.data;
        console.log("美团数据加载成功:", result);
        meituanData.value = result;
      })
      .catch((error) => {
        console.error("美团数据加载失败:", error);
      })
  );

  // 4. 加载个人企业信息
  promises.push(
    axios
      .post("/api/personEnterprise/info", {
        idNumber: idNumber.value,
      })
      .then((response) => {
        const result = response.data;
        console.log("个人企业信息加载成功:", result);
        personEnterpriseInfo.value = result.data || [];
      })
      .catch((error) => {
        console.error("个人企业信息加载失败:", error);
      })
  );

  // 5. 加载本人地址交互频次数据
  promises.push(
    axios
      .post("/api/meituan/selfAddressFrequency", {
        phone: phone.value,
      })
      .then((response) => {
        const result = response.data;
        console.log("本人地址交互频次数据加载成功:", result);
        if (result.code === 200) {
          selfAddressFrequency.value = result.data || [];
        }
      })
      .catch((error) => {
        console.error("本人地址交互频次数据加载失败:", error);
      })
  );

  // 6.加载户籍信息
  promises.push(
    axios
      .post("/api/personInfo/findByIdNumber", {
        idNumber: idNumber.value,
      })
      .then((response) => {
        if (response.data.code === 200 && response.data.data.length > 0) {
          personalInfo.value = response.data.data[0];
        }
      })
      .catch((error) => {
        console.error("个人基本信息加载失败:", error);
      })
  );

  // 等待所有请求完成后再执行后续操作
  Promise.all(promises).then(() => {
    isDataLoaded.value = true; // 标记数据加载完成
    // 所有数据加载完毕，重置 cachedScore 以便重新计算
    cachedScore = null;
    // 所有数据加载完毕，现在可以安全地预测地址
    predictAddress();

    // 初始化图表
    initHomeTimeChartSmall();
  });
};

// 美团数据
const meituanData = ref(null);

// 获取去重后的房产数量
const getUniqueRealEstateCount = (realEstateList) => {
  if (!realEstateList || realEstateList.length === 0) return 0;
  const uniqueAddresses = new Set();
  realEstateList.forEach((item) => {
    if (item && item.address) uniqueAddresses.add(item.address);
  });
  return uniqueAddresses.size;
};

// 房产信息去重函数
const deduplicateRealEstate = (list) => {
  if (!list || list.length === 0) return [];
  const seen = new Set();
  return list.filter((item) => {
    if (!item || !item.address) return false;
    if (seen.has(item.address)) return false;
    seen.add(item.address);
    return true;
  });
};

// 预测最新居住地址
const predictAddress = () => {
  // 优先使用美团数据
  if (meituanData.value && meituanData.value.mostFrequentAddress) {
    predictedAddress.value = meituanData.value.mostFrequentAddress;
    return;
  }

  // 最终设为"无信息"
  predictedAddress.value = "无信息";
};

// 履行能力打分
let cachedScore = null;

const getPerformanceScore = () => {
  if (cachedScore === null) {
    // 确保数据已经加载完成
    if (!realEstateInfo.value || !filteredEnterpriseInfo.value) {
      return 0; // 或者返回一个默认值
    }

    // 检查是否有不动产信息
    const hasRealEstate = realEstateInfo.value && realEstateInfo.value.length > 0;

    // 检查是否有个人企业信息
    const hasEnterprise =
      filteredEnterpriseInfo.value && filteredEnterpriseInfo.value.length > 0;

    console.log("不动产信息:", realEstateInfo.value);
    console.log("企业信息:", filteredEnterpriseInfo.value);
    console.log("是否有不动产:", hasRealEstate);
    console.log("是否有企业:", hasEnterprise);

    if (hasRealEstate && hasEnterprise) {
      // 既有不动产又有企业信息，评分高
      cachedScore = 90;
    } else if (hasRealEstate || hasEnterprise) {
      // 只有不动产或只有企业信息，评分中等
      cachedScore = 70;
    } else {
      // 什么都没有，评分低
      cachedScore = 30;
    }
  }
  return cachedScore;
};

const getPerformanceText = () => {
  const score = getPerformanceScore();
  if (score >= 80) return "强";
  if (score >= 60) return "适中";
  return "薄弱";
};
// 获取履行能力等级文本（强/中/弱）
const getPerformanceLevel = () => {
  const score = getPerformanceScore();
  if (score >= 80) return "强";
  if (score >= 60) return "中";
  return "弱";
};
const getPerformanceColor = () => {
  const score = getPerformanceScore();
  if (score >= 80) return "#67c23a"; // 低风险 - 绿色
  if (score >= 60) return "#e6a23c"; // 中风险 - 橙黄色
  return "#f56c6c"; // 高风险 - 红色
};

// 根据时间判断时间段
const getTimeSegment = (timeStr) => {
  const date = new Date(timeStr);
  const hour = date.getHours();
  if (hour >= 18 && hour <= 22) return "晚上 18:00-22:00";
  if (hour >= 9 && hour <= 18) return "周末 9:00-18:00";
  if (date.getDay() === 0 || date.getDay() === 6) return "节假日 9:00-22:00";
  return "其他时间";
};

// 修改 initHomeTimeChartSmall - 使用 SongDaJuChuan 的样式
const initHomeTimeChartSmall = () => {
  if (!chartRefHomeTimeSmall.value) return;
  homeTimeInstanceSmall = echarts.init(chartRefHomeTimeSmall.value);

  // 获取美团数据中的高频时间
  const timeStr = meituanData.value?.mostFrequentTime || "2024-01-01T18:30:00";
  const date = new Date(timeStr);
  const hour = date.getHours();

  // 根据小时判断时间段
  let targetSegment = "";
  if (hour >= 18 && hour <= 22) {
    targetSegment = "晚上 18:00-22:00";
  } else if (hour >= 9 && hour <= 18) {
    targetSegment = "周末 9:00-18:00";
  } else if (date.getDay() === 0 || date.getDay() === 6) {
    targetSegment = "节假日 9:00-22:00";
  } else {
    targetSegment = "其他时间";
  }

  // 设置各时间段的值（目标段最大，其余随机）
  const segments = [
    "晚上 18:00-22:00",
    "周末 9:00-18:00",
    "节假日 9:00-22:00",
    "其他时间",
  ];

  // 定义固定的百分比值
  const percentages = {
    high: 56, // 高频段占比
    low1: 13, // 其他段占比
    low2: 14,
    low3: 17,
  };
  // 构建数据数组，按指定比例分配
  const data = segments.map((segment, index) => {
    if (segment === targetSegment) {
      return { name: segment, value: percentages.high };
    } else {
      // 按顺序分配剩余的百分比
      const remainingSegments = segments.filter((s) => s !== targetSegment);
      const remainingIndex = remainingSegments.indexOf(segment);

      switch (remainingIndex) {
        case 0:
          return { name: segment, value: percentages.low1 };
        case 1:
          return { name: segment, value: percentages.low2 };
        case 2:
          return { name: segment, value: percentages.low3 };
        default:
          return { name: segment, value: 0 };
      }
    }
  });
  const option = {
    tooltip: {
      trigger: "item",
      formatter: function (params) {
        return `${params.name}: ${params.value}%`;
      },
    },
    legend: {
      orient: "horizontal",
      left: "center",
      bottom: "0",
      data: segments,
      textStyle: {
        fontSize: 8,
      },
      formatter: function (name) {
        const item = data.find((d) => d.name === name);
        return `${name} (${item.value}%)`;
      },
      itemGap: 5,
      itemWidth: 10,
      itemHeight: 10,
      labelLine: {
        show: true,
        length: 20,
        length2: 10,
        lineStyle: {
          color: "#999",
          width: 1,
        },
      },
    },
    series: [
      {
        name: "在家时间段",
        type: "pie",
        radius: ["0%", "70%"],
        center: ["50%", "40%"],
        data: data,
        label: {
          show: true,
        },
        labelLine: {
          show: true,
        },
        emphasis: {
          itemStyle: {
            shadowBlur: 5,
            shadowOffsetX: 0,
            shadowColor: "rgba(0, 0, 0, 0.3)",
          },
        },
      },
    ],
  };

  homeTimeInstanceSmall.setOption(option);
};

onMounted(() => {
  loadData();
});
</script>

<style scoped>
.mb-3 {
  margin-bottom: 20px;
}

.card-header {
  font-weight: bold;
}

.card-contain {
  margin-bottom: 15px;
  flex: 1;
  min-width: 200px;
  border: 1px solid #ebeef5;
  padding: 10px;
  border-radius: 6px;
}

.container-wrap {
  width: 100%;
  /* 可选，块级元素默认100%，可省略 */
}

.columns {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
  flex-wrap: nowrap;
  align-items: flex-start;
  gap: 1.5rem;
}

.column {
  flex-grow: 1;
  flex-shrink: 1;
}
</style>
